import sys  
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLineEdit  
from paho.mqtt import client as mqtt_client  
import uuid 
class MqttClient(QWidget):  
    def __init__(self):  
        super().__init__()  
  
        self.initUI()  
  
    def initUI(self):  
        layout = QVBoxLayout()  
  
        self.message_box = QLineEdit()  
        layout.addWidget(self.message_box)  
  
        self.send_button = QPushButton("Send")  
        self.send_button.clicked.connect(self.sendMessage)  
        layout.addWidget(self.send_button)  
  
        self.setLayout(layout)  
  
        self.client = mqtt_client.Client(str(uuid.uuid4()))  
        self.client.on_connect = self.on_connect    # 返回连接状态的回调函数
        self.client.on_message = self.on_message   # 返回订阅消息回调函数
        self.client.username_pw_set("client1", "password")  # mqtt服务器账号密码
        self.client.connect("127.0.0.1", 1883, 60)  
        # self.client.connect("10.0.0.90", 1883, 60)  
        self.client.loop_start()  
        self.client.subscribe("LwIP-TopicTest") 
  
    def sendMessage(self):  
        message = self.message_box.text().strip()  
        print(message)
        testList=[0x01,0x02]
        if message:  
            # self.client.publish("Test/Topic1", bytes(testList))  
            # self.client.publish("Test/Topic1", 'hlly333')  
            self.client.publish("Test/Topic1", message)  
            # self.message_box.setText("")  
    def on_connect(self, client, userdata, flags, rc):  
        print(f"Connected with result code {rc}")  
        # client.subscribe("test/topic")  
        # client.publish("test/topic", "Hello MQTT!")  
  
    def on_message(self, client, userdata, msg):  
        print(f"{msg.topic} {msg.payload}") 

if __name__ == '__main__':  
    app = QApplication(sys.argv)  
    ex = MqttClient()  
    ex.show()  
    sys.exit(app.exec_())